package com.ruoyi.event.config;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.event.service.impl.EventInfoListServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WxSecurityUtils {


    @Value("${wx.miniapp.appid}")
    private String appid;
    @Value("${wx.miniapp.secret}")
    private String secret;

    private static final Logger log = LoggerFactory.getLogger(EventInfoListServiceImpl.class);

    // 微信API配置（替换为自己的小程序信息）
    private static final String APPID = "wx4982ba1a4926ff42";
    private static final String SECRET = "386563d14d6e0d379a2af9543ef53edf";
    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
    private static final String MSG_SEC_CHECK_URL = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=%s";
    private static final String IMG_SEC_CHECK_URL = "https://api.weixin.qq.com/wxa/media_check_async?access_token=%s";

    private static RestTemplate restTemplate = new RestTemplate();

    // 获取access_token（实际项目中需加缓存，避免频繁调用）
    private static String getAccessToken() {
        String url = String.format(ACCESS_TOKEN_URL, APPID, SECRET);
        log.info("url{}", url);
        Map<String, Object> result = restTemplate.getForObject(url, Map.class);
        return result.get("access_token").toString();
    }

    /**
     * 文本安全检测
     * @param content 待检测文本
     * @return true=安全，false=违规
     */
    public static boolean checkText(String content,String openId) {
        try {
            String accessToken = getAccessToken();
            String url = String.format(MSG_SEC_CHECK_URL, accessToken);
            log.info("url{}", url);
//            Map<String, Object> request = new HashMap<>();
//            request.put("content", content);
//            request.put("version", 2);
//            request.put("scene", 1);
//            request.put("openid", "o-wxv1xJlIlicMuzEZJaUgOKGhd4");

            JSONObject requestBody = new JSONObject();
            requestBody.put("openid",openId); // 真实 openid
            requestBody.put("scene", 1); // 活动发布场景
            requestBody.put("version", 2);
            requestBody.put("content", content);


            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> entity = new HttpEntity<>(requestBody.toString(), headers);

            log.info(entity.toString());
            Map<String, Object> response = restTemplate.postForObject(url, entity, JSONObject.class);
            log.info(response.toString());
            // 微信返回码：0=通过，其他=违规
            return (Integer) response.get("errcode") == 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false; // 调用失败默认视为违规
        }
    }

    /**
     * 图片安全检测
     * @param openId 待检测图片文件
     * @return true=安全，false=违规
     */
    public static boolean checkImage(String openId,String imageUrl) {
        try {
            String accessToken = getAccessToken();
            String url = String.format(IMG_SEC_CHECK_URL, accessToken);
            log.info("url{}", url);

            JSONObject requestBody = new JSONObject();
            requestBody.put("openid", openId); // 真实 openid
            requestBody.put("version", 2); // 活动发布场景
            requestBody.put("scene", 1);
            requestBody.put("media_type", 2);
            requestBody.put("media_url", imageUrl);


            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> entity = new HttpEntity<>(requestBody.toString(), headers);

            log.info(entity.toString());
            Map<String, Object> response = restTemplate.postForObject(url, entity, JSONObject.class);
            log.info(response.toString());

            // 微信返回码：0=通过，其他=违规
            return (Integer) response.get("errcode") == 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false; // 调用失败默认视为违规
        }
    }
}